<?php
include_once 'app/until/GFW_database.php';

class Db_Mail extends Model_Db_Core {

	protected  $con = null;
	protected  $mail = null;

	function __construct(){
		//
	}

	public function GetAllMails($id, $limit = 25, $offset = 0){
		$sql = 'Select u.username, m.id, m.subject, m.post_date, m.priority, m.text, m.status from mails m, user u where `to` = "'.$id.'" and m.from = u.id ORDER BY  `post_date` DESC LIMIT '.$offset.','.$limit;
		
		parent::setSqlManuel($sql);
	    $this->mail = parent::result();
		return $this->mail;
	}
	public function delMail($user_id,$mail_id){
		$sql = "DELETE FROM `mails` WHERE `id` = ".$mail_id." and `to` = ".$user_id;

		parent::setSqlManuel($sql);
	    $this->mail = parent::result();
	    		
		return $this->mail;
	}
	public function SendeMail($from,$to,$subject = "Kein Betreff",$text,$piroty = 0,$answer_id = 0){
		   
		parent::setInsert("Db_mails");
		 	 	
		$this->value['from'] = $from;
		$this->value['to'] = $to;
		$this->value['subject'] = $subject;
		$this->value['post_date'] = "NOW()";
		$this->value['text'] = $text;
		$this->value['priority'] = $piroty;
		$this->value['status'] = 0;
		$this->value['answer_id'] = $answer_id;
				
	    $status = $this->writeToDb();
	   
	    return $status;
	}
	public function GetCountUnReadedMails($user_id){		
	    $filter  = array('mails.to'=> $user_id,'mails.status'=> 0);
	    $select  = array("count(id) as mails");
	    
	    parent::getSQLResult("Db_mails",$filter,$select);
	    $this->mails = parent::result(1);

	    return $this->mails;		
	}
	public function GetMail($user_id,$id){
	    $sql = 'Select mails.*, u.username, mails.answer_id as answer_id from mails, user u where mails.`to` = "'.$user_id.'" and mails.id = '.$id.' and mails.from = u.id LIMIT 0,1';
		
		parent::setSqlManuel($sql);
	    $this->mail = parent::result(1);
	    		
		return $this->mail;
	}
	public function GetLastMail($user_id,$answer){
		$sql = 'Select mails.*, u.username from mails, user u where mails.`from` = "'.$user_id.'" and mails.id = '.$answer.' and mails.from = u.id LIMIT 0,1';
		
		parent::setSqlManuel($sql);
	    $this->mail = parent::result(1);
	    		
		return $this->mail;
	}
	public function ChangeOnReaded($id){
		parent::setInsert("Db_mails");
		 	 	
		$this->value['status'] = 1;
		$this->value['id'] = $id;
				
	    $status = $this->writeToDb();
	   
	    return $status;		 
	}

}

?>